package com.bjpowernode.payment01.util;

import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.swing.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Pkipair {
    //生成签名
    public String signMsg(String signMsg) {
        String base64="";
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12");
            //加载商户的私钥证书
            String file = Pkipair.class.getResource("10012140356.pfx").getPath().replaceAll("%20", " ");
            System.out.println(file);
            FileInputStream ksfis = new FileInputStream(file);
            BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
            char[] keyPwd = "123456".toCharArray();
            ks.load(ksbufin,keyPwd);
            PrivateKey prik = (PrivateKey) ks.getKey("test-alias",keyPwd);
            Signature signature  = Signature.getInstance("SHA256withRSA");
            signature.initSign(prik);
            signature.update(signMsg.getBytes("utf-8"));
            Base64 encoder = new Base64();
            base64 = encoder.encodeAsString(signature.sign());
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return base64;
    }
    //验证签名
    public boolean enCodeByCer(String val,String msg){
        boolean flag = false;
        try{
            String file = Pkipair.class.getResource("99bill[1].cert.rsa.20140803.cer").toURI().getPath();//99bill[1].cert.rsa.20140803.cer
            System.out.println(file);                       //  99bill.cert.rsa.20140803.cer
            FileInputStream inStream = new FileInputStream(file);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

            PublicKey pk = cert.getPublicKey();

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(pk);
            signature.update(val.getBytes());

            //sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            //System.out.println(new String(decoder.decodeBuffer(msg)));
            //flag = signature.verify(decoder.decodeBuffer(msg));

            Base64 decoder = new Base64();
            flag = signature.verify(decoder.decode(msg));
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }
}
